import React, { useState, useEffect } from 'react';
import { View, Text, Image, StyleSheet, TextInput, Pressable, ScrollView, Keyboard, TouchableWithoutFeedback, KeyboardAvoidingView, Platform } from 'react-native';
import CommentInput from './CommentInput';
import Icon from 'react-native-vector-icons/FontAwesome';
import Icon1 from 'react-native-vector-icons/AntDesign';
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Modal } from 'react-native';
import ImageViewer from 'react-native-image-zoom-viewer';
const PostDetail = ({ route }) => {
  const [comments, setComments] = useState([
    // 示例评论数据
    { id: '1', username: '评论者A', content: '这是评论内容A...', avatar: 'https://placekitten.com/200/200' },
    // ...更多评论
  ]);
  const [commentsNumber, setCommentsNumber] = useState('');
  const [isKeyboardVisible, setIsKeyboardVisible] = useState(false);
  const { postId } = route.params;
  const [post, setPost] = useState({});
  const [postImg, setPostImg] = useState(null);
  const [userInfo, setUserInfo] = useState({});
  const [time, setTime] = useState(0);
  const [likes, setLikes] = useState('');
  const [liked, setLiked] = useState('');
  const [mark, setMarked] = useState('');
  const [collect, setCollect] = useState('');
  const [isImageViewVisible, setImageViewVisible] = useState(false);
  const getFormattedCurrentTime = () => {
    const now = new Date(); // 获取当前时间
    const year = now.getFullYear(); // 年
    const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月，月份是从0开始计数的
    const day = now.getDate().toString().padStart(2, '0'); // 日
    const hours = now.getHours().toString().padStart(2, '0'); // 时
    const minutes = now.getMinutes().toString().padStart(2, '0'); // 分
    const seconds = now.getSeconds().toString().padStart(2, '0'); // 秒

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
  const addNewComment = (comment) => {
    const currentTime = getFormattedCurrentTime();
    setTime(currentTime)
    if (comment != '') {
      axios.post('http://47.111.227.58:3000/dynamic/addcomments', {
        data: {
          dy_id: postId,
          username: userInfo.username,
          phone: userInfo.phone,
          userImg: userInfo.imgUrl,
          content: comment,
          uploadTime: time
        }
      }).then(res => {
        console.log(res.data)
        setCommentsNumber(Number(commentsNumber) + 1);
        axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicComments', {
          data: {
            id: postId,
            comment: Number(commentsNumber) + 1
          }
        }).then(res => {
          console.log(res.data);
          axios.post('http://47.111.227.58:3000/dynamic/updataIdCharacter', {
            data: {
              character: Number(userInfo.characters) + 1,
              id: userInfo.id
            }
          }).then(res => {
            console.log(res.data);
            userInfo.characters = Number(userInfo.characters) + 1
            AsyncStorage.setItem('userInfo', JSON.stringify(userInfo));
          });
        });
      })
    }
    const newComment = {
      dy_id: postId,
      username: userInfo.username,
      phone: userInfo.phone,
      userImg: userInfo.imgUrl,
      content: comment,
      uploadTime: time
    };
    setComments([...comments, newComment]);
  };
  // 点击空白处隐藏键盘和发送按钮的函数
  const handleHideKeyboard = () => {
    setIsKeyboardVisible(false);
    Keyboard.dismiss();
  };
  const handleDeletePost = (index) => {
    axios.post('http://47.111.227.58:3000/dynamic/deleteUserDynamic', {
      id: index
    })
      .then(res => {
        console.log(res.data);
        navigation.navigate('Pyq');
        // getDynamicList()
      })
      .catch(error => {
        console.error(error);
      });
  }
  const handleDeleteCommit = (index) => {
    axios.post('http://47.111.227.58:3000/dynamic/deletcomment', {
      id: index
    })
      .then(res => {
        console.log(res.data);
        getCommentList()
        setCommentsNumber(Number(commentsNumber) - 1);
        axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicComments', {
          data: {
            id: postId,
            comment: Number(commentsNumber) - 1
          }
        }).then(res => {
          console.log(res.data);
        });
      })
      .catch(error => {
        console.error(error);
      });
  }
  const handleLike = () => {
    if (liked) {
      // 如果用户已经点过赞，那么再次点击就取消点赞
      setLikes(Number(likes) - 1);
      setLiked(false);
      axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicLikes', {
        data: {
          id: post.id,
          likes: Number(likes) - 1
        }
      }).then(res => {
        console.log(res.data);
        // 更新点赞用户列表
        axios.post('http://47.111.227.58:3000/dynamic/updateLikedUsers', {
          postId: post.id,
          userId: userInfo.username
        }).then(res => {
          console.log(res.data);
        });
      });
    } else {
      // 如果用户还没点过赞，那么点击就增加点赞
      setLikes(Number(likes) + 1);
      setLiked(true);
      axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicLikes', {
        data: {
          id: post.id,
          likes: Number(likes) + 1
        }
      }).then(res => {
        console.log(res.data);
        // 更新点赞用户列表
        axios.post('http://47.111.227.58:3000/dynamic/updateLikedUsers', {
          postId: post.id,
          userId: userInfo.username
        }).then(res => {
          console.log(res.data);
        });
      });
    }
  };
  const handleMarked = () => {
    if (mark) {
      setMarked(false);
      axios.post('http://47.111.227.58:3000/dynamic/updateMarkUsers', {
        postId: post.id,
        userId: userInfo.username
      }).then(res => {
        console.log(res.data);
      });
    } else {
      setMarked(true);
      axios.post('http://47.111.227.58:3000/dynamic/updateMarkUsers', {
        postId: post.id,
        userId: userInfo.username
      }).then(res => {
        console.log(res.data);
      });
    }
  };
  const handleCollect = () => {
    if (collect) {
      setCollect(false);
      axios.post('http://47.111.227.58:3000/dynamic/updateCollectUsers', {
        postId: post.id,
        userId: userInfo.username
      }).then(res => {
        console.log(res.data);
      });
    } else {
      setCollect(true);
      axios.post('http://47.111.227.58:3000/dynamic/updateCollectUsers', {
        postId: post.id,
        userId: userInfo.username
      }).then(res => {
        console.log(res.data);
      });
    }
  };
  const getDynamicList = async () => {
    axios.post('http://47.111.227.58:3000/dynamic/searchDynamic', {
      data: {
        id: postId
      },
    })
      .then((res) => {
        // console.log(res.data[0]);
        setPost(res.data[0])
        setPostImg(res.data[0].imgUrl)
        setLikes(res.data[0].likes)
        const initialLiked = res.data[0].likedUsers?.split(',').includes(userInfo.username);
        setLiked(initialLiked);
        setCommentsNumber(res.data[0].comments)
        const initialMarked = res.data[0].markUsers?.split(',').includes(userInfo.username);
        setMarked(initialMarked)
        const initialCollected = res.data[0].collectUsers?.split(',').includes(userInfo.username);
        setCollect(initialCollected)
        // setComments(response.data);
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  };
  const getCommentList = async () => {
    axios.post('http://47.111.227.58:3000/dynamic/getComments', {
      data: {
        dy_id: postId
      },
    })
      .then((res) => {
        // console.log(res.data);
        setComments(res.data.data)
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  };
  useEffect(() => {
    (async () => {
      console.log('postId:', postId);
      const userinfo = await AsyncStorage.getItem('userInfo');
      if (userinfo) {
        setUserInfo(JSON.parse(userinfo));
      }

      // await getDynamicList()
      await getCommentList()
      // 监听键盘显示和隐藏事件
      const keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', () => {
        setIsKeyboardVisible(true);
      });
      const keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {
        setIsKeyboardVisible(true);
      });

      // 清理监听器
      return () => {
        keyboardDidShowListener.remove();
        keyboardDidHideListener.remove();
      };
    })();
  }, []);
  useEffect(() => {
    if (userInfo.username) {
      getDynamicList();
    }
  }, [userInfo]);
  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      keyboardVerticalOffset={Platform.OS === 'ios' ? 90 : 0}
    >
      <TouchableWithoutFeedback onPress={handleHideKeyboard}>
        <ScrollView style={styles.container} keyboardShouldPersistTaps='handled'>
          <View style={styles.postContainer}>
            <View style={styles.header}>
              <Image style={styles.avatar} source={{ uri: post.userImg }} />
              <Text style={styles.username}>{post.username}</Text>
              <Text style={styles.uploadTime}>{post.uploadTime}</Text>
            </View>
            <Text style={styles.postContent}>{post.desc}</Text>
            <Pressable onPress={() => setImageViewVisible(true) }>
              {postImg && (
                <Image source={{ uri: postImg }} style={styles.messageImage} />
              )}
            </Pressable>
            <Pressable onPress={() => setImageViewVisible(false)}>
              <Modal visible={isImageViewVisible} transparent={true}>
                <ImageViewer imageUrls={[{ url: postImg }]} />
              </Modal>
            </Pressable>
            <Text style={styles.boardText}>#{post.board}</Text>
            <View style={styles.interactionBar}>
              <View style={styles.interactionLeft}>
                <Icon name="external-link" size={20} color="#777777" />
                <Text style={styles.interactionText}>分享</Text>
                <Pressable style={styles.likeButton} onPress={handleCollect}>
                  <Icon name={collect ? 'star' : 'star-o'} size={20} color={collect ? '#5D81D0' : '#777777'} />
                  <Text style={[styles.interactionText, { color: collect ? '#5D81D0' : '#777777' }]}>{collect ? '取消' : '收藏'}</Text>
                </Pressable>
                <Pressable style={styles.likeButton} onPress={handleMarked}>
                  <Icon1 name={mark ? 'tags' : 'tagso'} size={20} color={mark ? '#5D81D0' : '#777777'} />
                  <Text style={[styles.interactionText, { color: mark ? '#5D81D0' : '#777777' }]}>{mark ? '弃坑' : '马住'}</Text>
                </Pressable>
              </View>
              <View style={styles.interactionRight}>
                <Icon name="certificate" size={20} color="#777777" />
                <Text style={styles.interactionText}>赞赏</Text>
                <Pressable style={styles.likeButton} onPress={handleLike}>
                  <Icon name={liked ? 'thumbs-up' : 'thumbs-o-up'} size={20} color={liked ? '#FE4F37' : '#777777'} />
                  <Text style={[styles.interactionText, { color: liked ? '#FE4F37' : '#777777' }]}>{likes > 0 ? likes : '点赞'}</Text>
                </Pressable>
                {post.username === userInfo.username && (
                  <Pressable onPress={() => handleDeletePost(post.id)} style={styles.likeButton}>
                    <Text>删除</Text>
                  </Pressable>
                )}
              </View>
            </View>
          </View>
          <View style={styles.commentsContainer}>
            <Text style={styles.commentsHeader}>共 {comments.length} 条评论</Text>
            {comments.map((comment) => (
              <View key={comment.id} style={styles.commentItem}>
                <Image style={styles.commentAvatar} source={{ uri: comment.userImg }} />
                <View style={styles.commentContent}>
                  <Text style={styles.commentUsername}>{comment.username}</Text>
                  <Text>{comment.content}</Text>
                </View>
                <Pressable style={styles.likeWrapper}>
                  <Icon name="thumbs-o-up" size={18} color="#b8b8b8" />
                </Pressable>
                {comment.username === userInfo.username && (
                  <Pressable onPress={() => handleDeleteCommit(comment.id)} style={styles.likeButton}>
                    <Text>删除</Text>
                  </Pressable>
                )}
              </View>
            ))}
          </View>
          {/* ...帖子内容和评论列表 */}
        </ScrollView>
      </TouchableWithoutFeedback>
      <CommentInput
        onCommentSubmit={addNewComment}
        isKeyboardVisible={isKeyboardVisible}
        setIsKeyboardVisible={setIsKeyboardVisible}
        style={styles.commentInput}
      />
    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f0f0f0',
  },
  postContainer: {
    backgroundColor: '#fff',
    padding: 15,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  avatar: {
    width: 50,
    height: 50,
    borderRadius: 25,
  },
  username: {
    fontWeight: 'bold',
    fontSize: 16,
    marginLeft: 10,
  },
  uploadTime: {
    // fontWeight: 'bold',
    color: '#b8b8b8',
    fontSize: 12,
    marginLeft: 'auto',
    marginRight: 0,
  },
  postContent: {
    marginTop: 8,
  },
  messageImage: {
    width: '70%',
    height: 170,
    borderRadius: 5,
    marginBottom: 5,
    borderWidth: 1,
    borderColor: '#ddd',
    marginBottom: 10,
  },
  boardText: {
    height: 25,
    width: 60,
    backgroundColor: '#DDE1EA',
    color: '#576B94',
    marginBottom: 5,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    fontSize: 12,
    // fontWeight: 'bold',
  },
  interactionBar: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: 15,
  },
  interactionLeft: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  interactionRight: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  interactionText: {
    fontSize: 12,
    color: '#777777',
    marginLeft: 5,
    marginRight: 10,
  },
  likeButton: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  commentsContainer: {
    backgroundColor: '#f0f0f0',
    paddingVertical: 10,
  },
  commentsHeader: {
    fontSize: 14,
    marginLeft: 15,
    marginBottom: 10,
  },
  commentItem: {
    flexDirection: 'row',
    padding: 15,
    backgroundColor: '#f0f0f0',
    borderBottomWidth: 1,
    borderBottomColor: '#ececec',
    alignItems: 'center',
  },
  commentAvatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
  },
  commentUsername: {
    fontWeight: 'bold',
  },
  commentContent: {
    flex: 1,
    marginLeft: 10,
  },
  likeWrapper: {
    padding: 8,
  },
  openCommentBoxButton: {
    padding: 10,
    borderTopWidth: 1,
    borderTopColor: '#ddd',
    alignItems: 'center',
  },
  openCommentBoxText: {
    color: '#007bff',
  },
  commentBox: {
    padding: 15,
    borderTopWidth: 1,
    borderTopColor: '#ddd',
  },
  commentInput: {
    position: 'absolute',
    bottom: 0,
    width: '100%',
  },
});

export default PostDetail;
